using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using ShopForWeb.Dto.AjaxModels;
using ShopForWeb.Service;
using ShopForWeb.UI.Filters;

namespace ShopForWeb.UI.Controllers;

[Route("identity")]

public class IdentityController : Controller
{
  private UserService _service;
  public IdentityController(UserService service)
  {
    _service = service;
  }

  [HttpPost("login")]
  public async Task<IActionResult> GetByLogin(string phone, string password)
  {
    var uvm = await _service.GetByLoginAsync(phone, password);
    if (uvm is not null)
    {


      var claims = new List<Claim>()
      {
        new Claim(ClaimTypes.Name,uvm.Name),
        new Claim(ClaimTypes.Sid,uvm.UserID.ToString().Trim()),
        new Claim(ClaimTypes.Role,"user"),
        new Claim(ClaimTypes.Role,"vip")
      };

      //制作通行证
      var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

      //载体
      var principal = new ClaimsPrincipal(identity);
      //登录存根
      await HttpContext.SignInAsync(
        CookieAuthenticationDefaults.AuthenticationScheme,  //登录方式
        principal,  //载体
        new AuthenticationProperties()  //关于cookie登录方式的扩展设定
        {
          IsPersistent = true,  //可持久化
          AllowRefresh = true   //可刷新
        }
      );

      return Json(new ResponseAjaxModel()
      {
        Status = 0,
        Message = $"欢迎{uvm.Name}的到来"
      });
    }
    else
    {
      return Json(new ResponseAjaxModel()
      {
        Status = 1,
        Message = "查无此人"
      });
    }
  }
  [UserInfoFiler]
  [HttpGet("login")]
  public IActionResult GetIndex()
  {
    return View();
  }

  [Route("user/denied")]
  public IActionResult AccessDenied()
  {
    return Redirect("/");
  }

}
